<?php

namespace App\Observers;

use App\Models\Adverti;
use App\Models\AdvertisPositions;
use Illuminate\Support\Facades\Redis;

class AdvertiObserver
{
    /**
     * 监听广告更新事件.
     *
     * @param  Adverti $adverti
     * @return void
     */
    public function saved(Adverti $adverti)
    {
        // 更新优惠券缓存
        $id = $adverti->id;
        $this->advertiCache($id, $adverti);

        // 更新广告位缓存
        $positionId = $adverti->position_id;
        $this->positionCache($positionId);
    }

    /**
     * 广告缓存
     *
     * @param  int $positionId 广告位id
     * @return void
     */
    protected function advertiCache($id, $adverti)
    {
        $time = time();
        Redis::hset("adverti:info:$id", 'updateTime', $time);
        Redis::hset("adverti:info:$id", 'info', serialize($adverti));
        Redis::hset("adverti:info:$id", 'budget', $adverti->day_budget);
    }

    /**
     * 广告位缓存
     *
     * @param  int $positionId 广告位id
     * @return void
     */
    protected function positionCache($positionId)
    {
        $time = time();

        Redis::hset("position:info:$positionId", 'updateTime', $time - 3600);
    }

    /**
     * 监听广告创建事件.
     *
     * @param  Adverti $adverti
     * @return void
     */
    public function created(Adverti $adverti)
    {
        //
    }

    /**
     * 监听广告删除事件.
     *
     * @param  Adverti $adverti
     * @return void
     */
    public function deleting(Adverti $adverti)
    {
        //
    }
}